package handler

import (
	"api/basic/config"
	"api/basic/pkg"
	"api/basic/pkg/jwt"
	"api/basic/proto/docker"
	"api/handler/request"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	filepath "path/filepath"
)

func Login(c *gin.Context) {
	var userreq request.UserLoginReq
	err := c.ShouldBind(&userreq)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "错误",
			"data": err.Error(),
		})
		return
	}
	r, err := config.Pb.UserLogin(c, &docker.UserLoginReq{Phone: userreq.Phone, Password: userreq.Password})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", r)
	claims := jwt.CustomClaims{ID: uint(r.UserId)}
	token, err := jwt.NewJWT("1").CreateToken(claims)
	if err != nil {
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "登录成功",
		"data": token,
	})
}

func Image(c *gin.Context) {
	// 单文件
	file, _ := c.FormFile("file")
	log.Println(file.Filename)
	if file.Size >= 3*1024*1024 {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "文件过大",
			"data": nil,
		})
		return

	}
	ext := filepath.Ext(file.Filename)
	fmt.Println(ext)
	if ext != ".pkg" && ext != ".jpg" {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "文件格式错误",
			"data": nil,
		})
		return
	}
	dst := "./basic/pkg/image" + file.Filename
	// 上传文件至指定的完整文件路径
	c.SaveUploadedFile(file, dst)
	pkg.Oss(dst+ext, dst)
	c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
}
